import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/entity/search/search_data_entiy.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/ui/widget/custom_refresh.dart';
import 'package:qianyi/wcao/kit/index.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../../network/http_config.dart';
import '../../../../../view_model/searcher/search_model.dart';

/// HACK: 社区-发现
class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with AutomaticKeepAliveClientMixin{
  final TextEditingController _searchController = TextEditingController();
  TokenController tokenController = Get.find();
  HomeTabController homeTabController = Get.find();
  final FocusNode focusNode = FocusNode();
  double heightContainer = 70.0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white, // AppBar背景颜色
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.black), // 返回按钮颜色
          onPressed: () {
            Navigator.pop(context);
            // performSearch(_searchController.text);
          },
        ),
        actions: <Widget>[
          Container(
            width: 250, // 设置搜索框宽度
            padding: EdgeInsets.symmetric(horizontal: 10), // 搜索框内边距
            child: TextField(
              focusNode: focusNode,
              controller: _searchController,
              decoration: InputDecoration(
                hintText: "请输入搜索内容",
                hintStyle: TextStyle(color: Colors.grey), // 提示文字颜色
                border: InputBorder.none, // 移除边框
                contentPadding: EdgeInsets.symmetric(vertical: 10), // 内容内边距
              ),
            ),
          ),
          IconButton(
            icon: Icon(Icons.search, color: Colors.black), // 搜索图标颜色
            onPressed: () {
              focusNode.unfocus();

              if(_searchController.text.length <= 0) {
                return;
              }
              Map<String,dynamic> params ={"uid":tokenController.uid,"keyword":_searchController.text};
              HttpManager.getInstance().request(url: '/platform/searchRecord/addSearchRecord',method: Method.post,params: params);
              HttpManager.getInstance().request(url: '/search/searchRecord/addSearchRecordData',method: Method.get,params: params);


              homeTabController.searchName = _searchController.text;
              _searchController.clear();
              Get.toNamed("/view_model/find/searcher");
            },
          ),
        ],
      ),
      body: GestureDetector(
        child: MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => SearchViewModel()),
          ],
          child: Consumer<SearchViewModel>(
            builder: (context, searchViewModel, child) {
              return CustomRefresh(
                controller: searchViewModel.refreshController,
                isMaterialHeader: true,
                enablePullUp: false,
                enablePullDown: true,
                onRefresh: () async {
                  searchViewModel.onRefresh();
                },
                onLoading: () async {
                  searchViewModel.onLoading();
                },
                child: tokenController.uid.length > 0
                    ? Column(
                  children: <Widget>[

                    SizedBox(height: 10),
                    Container(
                      padding: EdgeInsets.only(left: 10, right: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [Text("搜索历史"),
                              IconButton(onPressed: (){
                                setState(() {
                                  if(this.heightContainer == 150) {
                                    this.heightContainer = 80;

                                  } else {
                                    this.heightContainer = 150;

                                  }

                                });
                              }, icon: Icon(Icons.arrow_drop_down_circle_outlined))],
                          ),
                          IconButton(
                            icon: Icon(Icons.delete),
                            onPressed: () {
                              showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                  return AlertDialog(
                                    title: Text('确认删除'),
                                    content: Text('您确定要删除这些搜索记录吗？'),
                                    actions: <Widget>[
                                      TextButton(
                                        child: Text('取消'),
                                        onPressed: () {
                                          Navigator.of(context).pop(); // 关闭对话框
                                        },
                                      ),
                                      TextButton(
                                        child: Text('删除'),
                                        onPressed: () {
                                          Navigator.of(context).pop(); // 关闭对话框
                                          List<String> params = searchViewModel.allSearchRecord!;
                                          ;
                                          HttpManager.getInstance().request(url: '/platform/searchRecord/deleteSearchRecord?uid=${tokenController.uid}',method: Method.post,listParams: params).then((value) {
                                            searchViewModel.onRefresh();

                                          });

                                        },
                                      ),
                                    ],
                                  );
                                },
                              );

                            },
                          ),
                        ],
                      ),
                    ),

                    searchViewModel.allSearchRecord != null
                        ? AnimatedContainer(
                      curve: Curves.easeInOut,

                      duration: Duration(milliseconds: 300),height: heightContainer,
                        child: ClipRect(
                          child: SingleChildScrollView(
                            child: Wrap(

                              spacing: 5.0,
                              runSpacing: 5.0,
                              children: searchViewModel.allSearchRecord!.map((tag) {
                                return ActionChip(
                                  label: Text(tag),
                                  onPressed: () {
                                    _searchController.text = tag;
                                    if(_searchController.text.length <= 0) {
                                      return;
                                    }
                                    Map<String,dynamic> params ={"uid":tokenController.uid,"keyword":_searchController.text};
                                    HttpManager.getInstance().request(url: '/platform/searchRecord/addSearchRecord',method: Method.post,params: params);
                                    HttpManager.getInstance().request(url: '/search/searchRecord/addSearchRecordData',method: Method.get,params: params);


                                    homeTabController.searchName = _searchController.text;
                                    Get.toNamed("/view_model/find/searcher");
                                  },
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                    )

                        : Text("暂无搜索历史"),


                    SizedBox(height: 20),
                    Container(
                      padding: EdgeInsets.only(left: 10, right: 10),
                      child: Row(
                        children: [Text("热门搜索")],
                      ),
                    ),
                    Expanded(
                      child: SingleChildScrollView(
                        child: Column(
                          children: searchViewModel.datas.map((item) {
                            int index = searchViewModel.datas.indexOf(item);
                            Color backgroundColor;
                            if (index < 3) {
                              backgroundColor = Colors.amber; // 金色
                            } else if (index < 5) {
                              backgroundColor = Colors.amber.withOpacity(0.5); // 淡金色
                            } else {
                              backgroundColor = Colors.grey; // 灰色
                            }
                            return GestureDetector(
                              onTap: () {
                                _searchController.text = item.keyword;
                                if(_searchController.text.length <= 0) {
                                  return;
                                }
                                Map<String,dynamic> params ={"uid":tokenController.uid,"keyword":_searchController.text};
                                HttpManager.getInstance().request(url: '/platform/searchRecord/addSearchRecord',method: Method.post,params: params);
                                HttpManager.getInstance().request(url: '/search/searchRecord/addSearchRecordData',method: Method.get,params: params);


                                homeTabController.searchName = _searchController.text;
                                Get.toNamed("/view_model/find/searcher");
                              },
                              child: Padding(
                                padding: const EdgeInsets.all(10),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                                  children: [
                                    SizedBox(
                                      width: 20,
                                      height: 20,
                                      child: Chip(
                                        backgroundColor: backgroundColor,
                                        label: Text('${item.count}'),
                                      ),
                                    ),
                                    SizedBox(width: 16),
                                    Expanded(
                                      child: Text(item.keyword),
                                    ),
                                    SizedBox(width: 16),
                                    Text("${item.count}"),
                                  ],
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                    ),
                  ],
                )
                    : Text(""),
              );
            },
          ),
        ),
        onTap: (){
          focusNode.unfocus();

        },
      )
      ,
    );
  }

  void performSearch(String query) {
    print("Performing search for: $query");
    // Add the query to history and update UI
    setState(() {
      historyTags.add(query);
    });
  }

  void clearHistory() {
    setState(() {
      historyTags.clear();
    });
  }

  List<String> historyTags = ["我", "林允", "明月", "秦时"];
  List<Map<String, dynamic>> popularSearches = [
    {"name": "林允", "count": 3},
    {"name": "我", "count": 2},
    {"name": "秦时", "count": 1},
    {"name": "明月", "count": 1},
  ];

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}